package com.kongjs.common.mybatis.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.kongjs.common.mybatis.plugins.TenantPlugin;
import com.kongjs.common.mybatis.properties.PluginProperties;
import jakarta.annotation.Resource;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.kongjs.common.mybatis.plugins")
@EnableConfigurationProperties({PluginProperties.class})
public class MybatisConfig {
    @Resource
    private PluginProperties pluginProperties;
    @Resource
    private TenantPlugin tenantPlugin;

    /**
     * 添加分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        TenantLineInnerInterceptor tenantInterceptor = new TenantLineInnerInterceptor();
        tenantInterceptor.setTenantLineHandler(tenantPlugin);

        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();

        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        if (pluginProperties.getTenant().getEnabled()) {
            interceptor.addInnerInterceptor(tenantInterceptor);
        }

        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        // 如果配置多个插件, 切记分页最后添加
        // 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbType
        return interceptor;
    }
}
